﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using ProgrammingEducationSystem.Dto;
using ProgrammingEducationSystem.Models;
using ProgrammingEducationSystem.Services.IServices;
using ProgrammingEducationSystem.Tools;
using System.Security.Claims;


//班级控制器
//只能教师和管理员访问
namespace ProgrammingEducationSystem.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ClassesController : ControllerBase
    {

        private readonly IMapper _mapper;
        private readonly IClassesService _classesService;

        public ClassesController(IMapper mapper, IClassesService classesService)
        {
            _mapper = mapper;
            _classesService = classesService;
        }

        //查询
        [HttpGet]
        [Authorize(AuthenticationSchemes = "Bearer")]
        public async Task<IActionResult> SelectClass() {
            var data = await _classesService.AllAsync();
            return Ok(
                ApiResult.Success(data)
                ) ;
        }


        //添加班级
        [HttpPost]
        [Authorize(AuthenticationSchemes = "Bearer")]
        [Authorize(Roles = "TEACHER")]
        public async Task<IActionResult> AddClass(ClassForCreateDto classForCreateDto) 
        {

            //获取教师Id
            var teachId = this.HttpContext.User.FindFirstValue("UserId");
            var @class = _mapper.Map<Class>(classForCreateDto);
            @class.TeacherId = teachId;
            await _classesService.AddClassAsync(@class);
            await _classesService.SaveAsync();
            return Ok(
                ApiResult.Success(@class,"班级添加成功")
                );
        }
        [HttpDelete("{classId}")]
        //删除班级
        public async Task<IActionResult> Delete(Guid classid)
        {
            await _classesService.DeleteAsync(classid);
            await _classesService.SaveAsync();
            return Ok(ApiResult.Success(null, "班级删除成功"));                    
        }
        //修改班级
        [HttpPut]
        public async Task<IActionResult> Update(ClassForUpdateDto classForUpdateDto) {
            var existingClass = await _classesService.GetById(classForUpdateDto.Id);

            if (existingClass == null)
            {
                return NotFound(ApiResult.Failure("班级不存在"));
            }

            _mapper.Map(classForUpdateDto, existingClass);

            _classesService.UpdateAsync(existingClass);
            await _classesService.SaveAsync();

            return Ok(ApiResult.Success(existingClass, "班级信息更新成功"));

        }
    }
}
